package com.ktgj.customer.domain.Insurance.dftModel;
import com.sun.crypto.provider.SunJCE;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class PayEncrypt
{
    private final String Algorithm = "DESede";

    private void PayEncrypt()
    {
        Security.addProvider(new SunJCE());
    }

    public String encryptMode(String key, String src)
            throws EncException
    {
        try
        {
            byte[] destbyte = encryptMode(key.getBytes("utf-8"), src.getBytes("utf-8"));
            BASE64Encoder base64en = new BASE64Encoder();
            return base64en.encode(destbyte);
        }
        catch (Exception e)
        {
            throw new EncException(1, "PayEncrypt", "encryptMode", "加密错误", null);
        }
    }

    public String decryptMode(String key, String src)
            throws EncException
    {
        src = src.replace(" ", "+");
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            byte[] srcbyte = decoder.decodeBuffer(src);
            byte[] destbyte = decryptMode(key.getBytes("utf-8"), srcbyte);
            return new String(destbyte);
        }
        catch (Exception e)
        {
            throw new EncException(1, "PayEncrypt", "encryptMode", "解密错误", null);
        }
    }

    public byte[] encryptMode(byte[] keybyte, byte[] src)
    {
        try
        {
            SecretKey deskey = new SecretKeySpec(keybyte, "DESede");


            Cipher c1 = Cipher.getInstance("DESede");
            c1.init(1, deskey);
            return c1.doFinal(src);
        }
        catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {}catch (NoSuchPaddingException localNoSuchPaddingException) {}catch (Exception localException) {}
        return null;
    }

    public byte[] decryptMode(byte[] keybyte, byte[] src)
    {
        try
        {
            SecretKey deskey = new SecretKeySpec(keybyte, "DESede");


            Cipher c1 = Cipher.getInstance("DESede");
            c1.init(2, deskey);
            return c1.doFinal(src);
        }
        catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {}catch (NoSuchPaddingException localNoSuchPaddingException) {}catch (Exception localException) {}
        return null;
    }

    public String byte2hex(byte[] b)
    {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++)
        {
            stmp = Integer.toHexString(b[n] & 0xFF);
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
            if (n < b.length - 1) {
                hs = hs + ":";
            }
        }
        return hs.toUpperCase();
    }
}
